//
//  WDOrientationManager.m
//  handle
//
//  Created by little People on 2023/6/28.
//

#import "WDOrientationManager.h"

@implementation WDOrientationManager
static WDOrientationManager *_OrientationManager = nil;
+ (instancetype)shareOrientationManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _OrientationManager = [[self alloc] init];
        
    });
    return _OrientationManager;
}

- (void)adjustingScreenOrientation
{
    UIInterfaceOrientation dori = [UIApplication sharedApplication].statusBarOrientation;
    if ([WDOrientationManager shareOrientationManager].currentDeviceOrientation == UIInterfaceOrientationMaskPortrait)
    {
        if (dori == UIInterfaceOrientationLandscapeLeft || dori == UIInterfaceOrientationLandscapeRight)
        {
            [self changeOrientation:UIInterfaceOrientationMaskPortrait interfaceOrientation:UIDeviceOrientationPortrait];
        }
    }
    else if ([WDOrientationManager shareOrientationManager].currentDeviceOrientation == UIInterfaceOrientationMaskLandscapeLeft)
    {
        if (dori == UIInterfaceOrientationPortraitUpsideDown)
        {
            
            [self changeOrientation:UIInterfaceOrientationMaskLandscapeLeft interfaceOrientation:UIDeviceOrientationLandscapeLeft];
        }
    }
    else if ([WDOrientationManager shareOrientationManager].currentDeviceOrientation == UIInterfaceOrientationMaskLandscapeRight)
    {
        if (dori == UIInterfaceOrientationPortraitUpsideDown)
        {
            
            [self changeOrientation:UIInterfaceOrientationMaskLandscapeRight interfaceOrientation:UIDeviceOrientationLandscapeRight];
        }
    }
    
}

- (void)changeOrientation:(UIInterfaceOrientationMask)orientation interfaceOrientation:(UIDeviceOrientation)interface
{
    
    if (@available(iOS 16.0, *)) {
        // setNeedsUpdateOfSupportedInterfaceOrientations 方法是 UIViewController 的方法
        [[[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController] setNeedsUpdateOfSupportedInterfaceOrientations];
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        // 屏幕方向
//        UIInterfaceOrientationMask orientation = UIInterfaceOrientationMaskPortrait;
        UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];
        // 开始切换
        [scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
//                    WDLog(@"错误:%@", error);
        }];
    }
    else{
//        [self interfaceOrientation:UIInterfaceOrientationPortrait];
        
        
        NSNumber *orientationTarget = [NSNumber numberWithInteger:interface];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
}

@end
